package com.hronline;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import kankan.wheel.widget.WheelView;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.adapter.LogLatenessAdapter;
import com.adapter.ReasonAdapter;
import com.delegate.LogLatenessDelegate;
import com.delegate.ManagerEmployeesDelegate;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.models.DefaultStartEndTime;
import com.models.HolidayYear;
import com.models.LogLateness;
import com.models.ReasonLateness;
import com.models.Status;
import com.parser.ManagerParser;

public class LogLatenessActivity extends Fragment implements LogLatenessDelegate {
	
	private Context context;
	private ManagerEmployeesDelegate delegate;
	
	private LogLatenessAdapter adapter;
	private LogLateness logLateness;
	
	private ProgressDialog loadingDialog;
	
	private String empId;
	private String empName;
	
	private Date defaultStartDate;
	private Date defaultEndDate;
	
	private View pickerView;
	private WheelView reasonWheel;
	
	private ArrayList<ReasonLateness> arrReason;
	private ArrayList<HolidayYear> arrHolidayYear;
	
	private String newReasonString	=	"ADD NEW REASON...";
	private String newReason	=	"";
	private int	indexReason;
	private int indexHolidayYear;
	
	public LogLatenessActivity(Context context, ManagerEmployeesDelegate delegate, String empId, String empName){
		this.context	=	context;
		this.delegate	=	delegate;
		this.empId		=	empId;
		this.empName	=	empName;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View fragmentView	=	inflater.inflate(R.layout.activity_log_lateness, container, false);
		
		loadingDialog	=	new ProgressDialog(this.context);
		loadingDialog.setMessage(Constant.LOADING_STRING);
		
		createNavigationbar(fragmentView);
		initDefaultStartEndDate();
		setUpControl(fragmentView);
		requestData();
		
		return fragmentView;
	}
	
	/*=================================================================*/
	/*============================INIT VIEW============================*/
	/*=================================================================*/
	
	/* this method is used to create navigation bar */
	private void createNavigationbar(View view){
		
		Button btnCancel	=	(Button)view.findViewById(R.id.btnCancel);
		Button btnSend		=	(Button)view.findViewById(R.id.btnSend);
		
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				didClickCancelButton();
			}
		});
		
		btnSend.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				didClickSendButton();
			}
		});
	}
	
	/* this method is used to setup control view */
	private void setUpControl(View view){
		
		TextView txtEmpName				=	(TextView)view.findViewById(R.id.txtNameItem);
		txtEmpName.setText(this.empName);
		
		this.logLateness	=	new LogLateness();
		
		
		this.logLateness.setStartDate(defaultStartDate);
		this.logLateness.setEndDate(defaultEndDate);
		
		ListView listView	=	(ListView)view.findViewById(R.id.logLatenessListView);
		adapter	=	new LogLatenessAdapter(this.context, this.logLateness, this);
		listView.setAdapter(adapter);
		
		pickerView		=	view.findViewById(R.id.layout_wheel);
		
		/* invisible this view */
		pickerView.setVisibility(View.INVISIBLE);
		
		reasonWheel		=	(WheelView)view.findViewById(R.id.wheel_reason);
		reasonWheel.setVisibleItems(4);
		
		Button btnDone	=	(Button)view.findViewById(R.id.btnDone);
		btnDone.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				didClickDoneButton();
			}
		});
	}
	
	/*=================================================================*/
	/*=============================SELECTOR============================*/
	/*=================================================================*/
	
	/* this method is used to handle when user click on cancel button */
	private void didClickCancelButton(){
		delegate.pop();
	}
	
	/* this method is used to handle when user click on send button */
	private void didClickSendButton(){
		
		if (isValidLogLateness()) {
			submitLogLateness();
		}
		
	}
	
	/* this method is used to check log lateness before sending to server */
	private boolean isValidLogLateness(){
		
		/* start date and end date is the same */
		if(logLateness.getStartDate().compareTo(logLateness.getEndDate()) == 0){
			Constant.showErrorMessage(this.context, "Please correct Expected & Actual date.");
			return false;
		}
		
		return true;
	}
	
	/* this method is used to init default start date and end date */
	@SuppressWarnings("deprecation")
	private void initDefaultStartEndDate(){
		
		defaultStartDate	=	new Date();
		defaultEndDate		=	new Date();
		
		defaultStartDate.setHours(9);
		defaultStartDate.setMinutes(0);
		
		defaultEndDate.setHours(9);
		defaultEndDate.setMinutes(0);
	}
	
	private String convertDateToString(Date date){
		
		SimpleDateFormat formater	=	new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		
		return formater.format(date);
		
	}
		
	/* this method is used to request data */
	private void requestData(){
		
		loadingDialog.show();
		
		String strStart	=	convertDateToString(defaultStartDate);
		getDefaultAbsenceStartEndTimes(empId, strStart, null);
	}
	
	/* this method is used to handle when user click on done button */
	private void didClickDoneButton(){
		ReasonLateness itemSelected	=	this.arrReason.get(reasonWheel.getCurrentItem());
		//open the dialog allow user add new reason lateness
		if(itemSelected.getDescription().equalsIgnoreCase(newReasonString)){
			
			displayPromptToAddNewReason();
			
		}
		else{// set the log lateness reason
			
			this.logLateness.setReason(itemSelected.getDescription());
			this.logLateness.setReasonId(itemSelected.getReasonId());
			adapter.setLogLateness(this.logLateness);
			adapter.notifyDataSetChanged();
			
		}
		
		/* dismiss view */
		hideReasonView();
	}
	
	/* this method is used to display holiday year dialog */
	private void displayHolidayYearSelection(){
		
		String[] items	=	new String[this.arrHolidayYear.size()];
		for (HolidayYear holidayYear : this.arrHolidayYear) {
			items[this.arrHolidayYear.indexOf(holidayYear)]	=	holidayYear.getName();
		}
		
		AlertDialog.Builder builder	=	new AlertDialog.Builder(this.context);
		builder.setTitle("Holiday Year");
		builder.setCancelable(true);
		
		builder.setSingleChoiceItems(items, indexHolidayYear, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				indexHolidayYear	=	which;
				HolidayYear itemSelected	=	arrHolidayYear.get(indexHolidayYear);
				logLateness.setYearId(itemSelected.getHolidayYearId());
				logLateness.setHolidayYear(itemSelected.getName());
				
				adapter.setLogLateness(logLateness);
				adapter.notifyDataSetChanged();
				
				dialog.dismiss();
			}
		});
		
		builder.show();
		
	}
	
	/* this method is used to display picker reason view */
	private void displayReasonView(){
		/* get size of device screen */
		Display display = getActivity().getWindowManager().getDefaultDisplay();
		Point size	=	getDisplaySize(display);
		int height = size.y;
		
		TranslateAnimation anim	=	new TranslateAnimation(0, 0, height, 0);
		anim.setDuration(700);
		anim.setAnimationListener(new AnimationListener() {
			
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				pickerView.setVisibility(View.VISIBLE);
			}
			
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
			}
		});
		pickerView.startAnimation(anim);
		
		pickerView.setVisibility(View.VISIBLE);
		
		ReasonAdapter reasonAdapter	=	new ReasonAdapter(this.context, this.arrReason);
		reasonWheel.setViewAdapter(reasonAdapter);
		reasonWheel.setCurrentItem(indexReason);
	}
	
	/* this method is used to get the size of device */
	private Point getDisplaySize(Display display) {
	    Point point = new Point();
	    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){    
	        return point;
	    }else{    
	        point.x = display.getWidth();
	        point.y = display.getHeight();
	    }
	    return point;
	}
	
	/* this method is used to hide picker reason view */
	private void hideReasonView(){
		/* get size of device screen */
		Display display = getActivity().getWindowManager().getDefaultDisplay();
		Point size	=	getDisplaySize(display);
		int height = size.y;
		
		TranslateAnimation anim	=	new TranslateAnimation(0, 0, 0, height);
		anim.setDuration(700);
		anim.setAnimationListener(new AnimationListener() {
			
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				pickerView.setVisibility(View.INVISIBLE);
			}
		});
		pickerView.startAnimation(anim);
	}
	
	/* this method is used to diplay prompt to enter new reason lateness */
	private void displayPromptToAddNewReason(){
		
		final EditText edtNewReason	=	new EditText(this.context);
		AlertDialog.Builder builder	=	new AlertDialog.Builder(this.context);
		builder.setTitle("ADD NEW LATENESS REASON");
		builder.setView(edtNewReason);
		builder.setCancelable(true);
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				newReason	=	edtNewReason.getText().toString();
				submitNewReason(newReason);
				dialog.dismiss();
			}
		});
		
		builder.show();
	}
	
	/* this method is used to display prompt date and time for user choosing */
	private void displayDateTimePrompt(final boolean isStartDate){
		
		LayoutInflater inflater	=	(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View dateTimeView		=	inflater.inflate(R.layout.date_time_picker_view, null);
		
		String title			=	(isStartDate)? "Expected Date" : "Actual Date";
		
		final DatePicker datePicker	=	(DatePicker)dateTimeView.findViewById(R.id.datePicker);
		final TimePicker timePicker	=	(TimePicker)dateTimeView.findViewById(R.id.timePicker);
		
		AlertDialog.Builder builder	=	new AlertDialog.Builder(this.context);
		builder.setTitle(title);
		builder.setCancelable(true);
		builder.setView(dateTimeView);
		builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				try {
					int day		=	datePicker.getDayOfMonth();
					int month	=	datePicker.getMonth();
					int year	=	datePicker.getYear();
					
					int hour	=	timePicker.getCurrentHour();
					int minute	=	timePicker.getCurrentMinute();
					
					SimpleDateFormat formatter	=	new SimpleDateFormat("yyyy MM dd HH:mm");
					Date selectedDate = formatter.parse(String.format("%d %d %d %d:%d", year, month + 1, day, hour, minute));
					
					if(isStartDate){ // set date for start date
						logLateness.setStartDate(selectedDate);
						
						//reset the end date follow the start date if the start date is greater than end date
						if(logLateness.getStartDate().after(logLateness.getEndDate())){
							logLateness.setEndDate(logLateness.getStartDate());
						}
					}
					else{ // set date for end date
						
						//reset start date follow end date if end date is lesser than start date
						if(selectedDate.before(logLateness.getStartDate())){
							logLateness.setStartDate(selectedDate);
						}
						
						logLateness.setEndDate(selectedDate);
					}
					
					adapter.setLogLateness(logLateness);
					adapter.notifyDataSetChanged();
					
					dialog.dismiss();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		builder.show();
		
	}
	
	/* this method is used to submit new reason to server */
	private void submitNewReason(String reason){
		
		if(isValidReason(reason)){
			submitNewLatenessReason(reason);
		}
		
	}
	
	/* this method is used to check the reason before submit to server */
	private boolean isValidReason(String reason){
		
		/* check the empty reason */
		if(reason.length() == 0){
			Constant.showErrorMessage(this.context, "Lateness reason cannot be empty.");
			return false;
		}
		else{
			/* check duplicate reason */
			for (ReasonLateness item : this.arrReason) {
				if(item.getDescription().equalsIgnoreCase(reason))
				{
					Constant.showErrorMessage(this.context, "Duplicate reason.");
					return false;
				}
			}
		}
		
		return true;
		
	}
	
	
	/*=================================================================*/
	/*=============================CALL API============================*/
	/*=================================================================*/
	
	
	/*===================GET DEFAULT START END TIMES====================*/
	
	/* this method is used to call api to get data from sever */
	private void getDefaultAbsenceStartEndTimes(String empId, String startDate, String endDate){
		
		String url;
		if(endDate != null){
			url	=	String.format("%sAbsence/GetDefaultAbsenceStartEndTimes?AuthorisationToken=%s&employeeId=%s&startDate=%s&endDate=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN, empId, startDate, endDate);
		}
		else{
			url	=	String.format("%sAbsence/GetDefaultAbsenceStartEndTimes?AuthorisationToken=%s&employeeId=%s&startDate=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN, empId, startDate);
		}
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.get(url, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				
				handleGetDefaultStartEndTimeSuccess(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				
				handleGetConnectionFail();
			}
			
		});
	}
	
	/* this method is used to handle when get default start end time success */
	@SuppressWarnings("deprecation")
	private void handleGetDefaultStartEndTimeSuccess(String result){
		
		DefaultStartEndTime item	=	ManagerParser.parseGetDefaultStartEndTime(result);
		if(item != null){
			
			Date startDate	=	new Date();
			startDate.setHours(0);
			startDate.setMinutes(0);
			startDate.setSeconds(0);
			
			Date endDate	=	new Date();
			endDate.setHours(23);
			endDate.setMinutes(59);
			endDate.setSeconds(59);
			
			if(!(item.getDay() == 1 && item.getHours() == 0 
					&& item.getDefaultStartTime().equalsIgnoreCase(convertDateToString(startDate))
					&& item.getDefaultEndTime().equalsIgnoreCase(convertDateToString(endDate)))){
				
				SimpleDateFormat formater	=	new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
				Date date;
				try {
					date = formater.parse(item.getDefaultStartTime());
					this.logLateness.setStartDate(date);	
					this.logLateness.setEndDate(this.logLateness.getStartDate());
					adapter.setLogLateness(this.logLateness);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			getLatenessReason();
		}
	}
	
	/*===================GET LATENESS REASONS====================*/
	
	/* this method is used to get reason */
	private void getLatenessReason(){
		String	url	=	String.format("%sAbsence/GetLatenessReasons?AuthorisationToken=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN);
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.get(url, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleGetReasonSuccess(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				handleGetConnectionFail();
			}
		});
	}
	
	/* this method is used to handle get lateness reason success */
	@SuppressWarnings("unchecked")
	private void handleGetReasonSuccess(String result){
		
		ArrayList<Object> arrResult	=	ManagerParser.parseReasonLateness(result);
		
		/* get status object */
		Status statusItem	=	(Status)arrResult.get(0);
		if(!isStatusError(statusItem, "GetLatenessReasons")){
			
			arrReason	=	(ArrayList<ReasonLateness>)arrResult.get(1);
			if(arrReason.size() > 0){
				
				if(newReason.length() == 0){
					ReasonLateness item	=	arrReason.get(0);
					this.logLateness.setReason(item.getDescription());
					this.logLateness.setReasonId(item.getReasonId());
					indexReason	=	1;
				}
				else{
					this.logLateness.setReason(newReason);
					for (ReasonLateness item : this.arrReason) {
						if(item.getDescription().equalsIgnoreCase(newReason)){
							this.logLateness.setReasonId(item.getReasonId());
							indexReason	=	this.arrReason.indexOf(item) + 1;
							break;
						}
					}
				}
				adapter.setLogLateness(logLateness);
				newReason	=	"";
				
				/* get the year holiday */
				getYearHoliday();
				
				/* adding the add new reason to arr reason */
				ReasonLateness item	=	new ReasonLateness();
				item.setDescription("ADD NEW REASON...");
				this.arrReason.add(0, item);
			}
		}
	}
	
	/*===================SUBMIT NEW LATENESS REASON====================*/
	
	/* this method is used to call api to add new lateness to server */
	private void submitNewLatenessReason(String newReason){
		
		loadingDialog.show();
		
		String url	=	String.format("%sAbsence/AddLatenessReason?AuthorisationToken=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN);
		
		RequestParams params	=	new RequestParams();
		params.put("details", newReason);
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.post(url, params, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleSubmitLatenessReasonSuccess(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				handleGetConnectionFail();
			}
			
		});
		
	}
	
	/* this method is used to handle when submit new lateness success */
	private void handleSubmitLatenessReasonSuccess(String result){
		
		Status item	=	ManagerParser.parseSubmitNewLatenessReason(result);
		if(!isStatusError(item, "AddLatenessReason")){
			if(item.statusCode != Constant.SUCCESS_CODE){
				Constant.showErrorMessage(this.context, item.getInternalMessage());
			}
			else{
				loadingDialog.dismiss();
			}
		}
	}
	
	/*=================GET YEAR HOLIDAY==================*/
	
	/* this method is used to get year holiday from server */
	private void getYearHoliday(){
		
		String url	=	String.format("%sAbsence/GetHolidayYearsForEmployee?AuthorisationToken=%s&employeeid=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN, empId);
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.get(url, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleGetYearHoliday(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				handleGetConnectionFail();
			}
			
		});
		
	}
	
	/* this method is used to handle get year holiday success */
	@SuppressWarnings("unchecked")
	private void handleGetYearHoliday(String result){
		
		ArrayList<Object> arrResult	=	ManagerParser.parseGetYearHoliday(result);
		
		/* get status object */
		Status statusItem	=	(Status)arrResult.get(0);
		if(!isStatusError(statusItem, "GetHolidayYearsForEmployee")){
			
			this.arrHolidayYear	=	(ArrayList<HolidayYear>)arrResult.get(1);
			
			for (HolidayYear holidayYear : arrHolidayYear) {
				if(holidayYear.isCurrentHolidayYear()){
					this.logLateness.setHolidayYear(holidayYear.getName());
					this.logLateness.setYearId(holidayYear.getHolidayYearId());
					indexHolidayYear	=	this.arrHolidayYear.indexOf(holidayYear);
					break;
				}
			}
			
			adapter.setLogLateness(this.logLateness);
			adapter.notifyDataSetChanged();
			loadingDialog.dismiss();
		}
	}
	
	/*==========SUBMIT LOG LATENESS TO SERVER============*/
	
	/* this method is used to submit log lateness to server  */
	private void submitLogLateness(){
		
		loadingDialog.show();
		
		String url	=	String.format("%sAbsence/LogLateness?AuthorisationToken=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN);
		
		RequestParams params	=	new RequestParams();
		params.put("holidayYearId", logLateness.getYearId());
		params.put("expectedDateTime", convertDateToString(logLateness.getStartDate()));
		params.put("actualDateTime", convertDateToString(logLateness.getEndDate()));
		params.put("reasonid", logLateness.getReasonId());
		params.put("details", logLateness.getDetails());
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.post(url, params, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleSubmitLogLatenessSuccess(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				handleGetConnectionFail();
			}
			
		});
	}
	
	/* private void handle submit log lateness success */
	private void handleSubmitLogLatenessSuccess(String result){
		Status item	=	ManagerParser.parseSubmitLateness(result);
		if(!isStatusError(item, "LogLateness")){
			if(item.statusCode != Constant.SUCCESS_CODE){
				Constant.showErrorMessage(this.context, item.getInternalMessage());
			}
			else{
				
				loadingDialog.dismiss();
				
				/* inform to dashboard to refresh data */
				Intent intent	=	new Intent(Constant.MUST_UPDATE_DASHBOARD);
				this.context.sendBroadcast(intent);
				
				Log.i("duylept", "log lateness success");
				
				delegate.pop();
			}
		}
	}
	
	/*===================HANDLE ERROR====================*/
	
	/* this method is used to handle when get connection fail */
	private void handleGetConnectionFail(){
		
		this.loadingDialog.dismiss();
		Constant.showErrorMessage(this.context, Constant.CANNOT_CONNECT_SERVER);
	}
	
	/* this method is used to check status of message return form server */
	private boolean isStatusError(Status statusItem, String apiCalling){
		
		/* dismiss the loading dialog */
		loadingDialog.dismiss();
		
		if(statusItem.statusCode >= Constant.IVALID_AUTHORIZED_TOKEN){
			String message	=	String.format("%s - API %s", statusItem.getStatusText(), apiCalling);
			
			AlertDialog.Builder builder	=	new AlertDialog.Builder(this.context);
			builder.setMessage(message);
			builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					delegate.openLoginPage();
				}
			});
			
			builder.show();
			
			return true;
		}
		
		return false;
	}

	
	/*=================================================================*/
	/*=============================DELEGATE============================*/
	/*=================================================================*/
	
	@Override
	public void didClickReasonRow() {
		// TODO Auto-generated method stub
		displayReasonView();
	}

	@Override
	public void didClickHolidayYearRow() {
		// TODO Auto-generated method stub
		displayHolidayYearSelection();
	}

	@Override
	public void didClickStartDateRow() {
		// TODO Auto-generated method stub
		displayDateTimePrompt(true);
	}

	@Override
	public void didClickEndDateRow() {
		// TODO Auto-generated method stub
		displayDateTimePrompt(false);
	}
}
